// ==UserScript==
// @name         Walmart Review
// @namespace    pacey
// @version      0.1
// @description  get aliexpress feedback
// @author       pacey
// @updateURL    https://gitee.com/great-pacey/tampermonkey/raw/master/walmart.review.user.js
// @match        https://www.walmart.com/reviews/*
// @match        https://www.walmart.com/seller/*
// @grant unsafeWindow
// @grant GM_setClipboard
// @grant GM_registerMenuCommand
// @connect gitee.com
// ==/UserScript==


function hasNextPage() {
    let result = false;
    try {
        result = !!(document.querySelector('nav .list li:last-child a').getAttribute('data-testid') === 'NextPage');
    } catch (error) {
        result = false;
    }
    return result;
}

function turnNextPage() {
    return new Promise(resolve => {
        document.querySelector('nav .list li:last-child a').click();
        setTimeout(resolve, 1500);
    })
}

function getCurrentPageItems() {
    const a = [].slice.call(document.querySelectorAll('main section div ul li .w_DK.w_DN'));
    return a.map(i => {
        const texts = i.querySelector('.w_DM>div:nth-child(2)').innerText.trim().split(/\n/);
        const title = texts.length > 1 ? texts[0] : '';
        const content = texts.length > 1 ? texts[1] : texts[0];
        return {
            star: i.querySelectorAll('span.black>i.ld-StarFill').length,
            createTime: i.querySelector('.w_DM>div:first-child>div:nth-child(2)').innerText.trim(),
            title: title,
            content: content
        };
    });
}

function getPageInBulk() {
    return new Promise(resolve => {
        let items = [];
        items = items.concat(getCurrentPageItems());
        function loop() {
            if (hasNextPage()) {
                turnNextPage().then(() => {
                    items = items.concat(getCurrentPageItems());
                    loop();
                })
            } else {
                resolve(items);
            }
        }
        loop();
    })
}

function run() {
    getPageInBulk().then(res => {
        console.log(res);
        unsafeWindow.data = res;
        unsafeWindow.times = res.map(i => i.createTime);
        let texts = res.map(i => {
            if (i.title) {
                return i.title + '\n' + i.content
            } else {
                return i.content;
            }
        }).filter(i => !!i).join('\n\n');
        GM_setClipboard(texts);
        alert('已复制');
    });
}

GM_registerMenuCommand('开始复制', run);